package com.blast.cn.persenter.splash

import android.view.View
import com.blast.cn.R
import com.wxl.common.base.WorkPresenter
import com.wxl.common.util.NetWorkUtils
import com.wxl.common.util.ObservableUtil
import com.wxl.common.util.Toll
import com.wxl.common.wiget.TipPop
import io.reactivex.ObservableOnSubscribe
import io.reactivex.functions.Action
import kotlinx.android.synthetic.main.activity_splash_layout.view.*

class CheckNetPresenter : WorkPresenter() {

    override fun onStartDoWork(vararg args: Any) {
        rootView.splashStartBtn.visibility = View.GONE
        rootView.splashCheckDesTextView.text = "正在连接网络..."
        ObservableUtil.doNext(ObservableOnSubscribe<Int>{
            if (NetWorkUtils.checkNet(rootView.context)) {
                it.onNext(0)
            } else if(NetWorkUtils.hasSimCard(rootView.context)){
                it.onNext(1)
            } else {
                it.onNext(2)
            }
        }, object : ObservableUtil.Companion.OnNextCallback<Int>() {
            override fun onNext(t: Int) {
                onCheckNetWorkResult(t)
            }
        })
    }


    private fun onCheckNetWorkResult(i:Int){
        when (i) {
            0 -> {
                checkNetWorkUseAvailable()
            }
            1 -> {
                TipPop.show(rootView.context, "网络连接失败，请检查网络后重试！", Action {
                    finish()
                }, Action {
                    onStartDoWork()
                })
            }
            2 ->{
                Toll.toll("没有检测到sim卡，网络不可用！")
                rootView.splashStartBtn.visibility = View.VISIBLE
            }
        }
    }


    private fun checkNetWorkUseAvailable() {
        if (NetWorkUtils.isNetWorkAvailable(rootView.context)) {
            rootView.splashCheckDesTextView.text = "网络连接成功！"
            doNext()
        } else {
            rootView.splashCheckDesTextView.text = "网络不可用！"
            rootView.splashStartBtn.visibility = View.VISIBLE
            rootView.splashCheckDesTextView.setTextColor(getResColor(R.color.image_selector_red))
        }
    }


}